package com.splic.product.service.impl.thirdRequest;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * ==========================
 * 开发：singe
 * 创建时间：2022-03-09 21:51
 * 版本: 1.0
 * 描述：逆地址接码
 *          根据经纬度定位城市
 * ==========================
 */
@Service
@Slf4j
public class PositioningCityRequestServiceImpl {


    private final String key = "5960001af604a5995b1b556c2ab125ee";
    private final String url = "https://restapi.amap.com/v3/geocode/regeo?location=lng,lat&key="+key+"&radius=100";

    private final String baiduKey = "87b2d685bef615f9992b28b76a8610fd";
    private final String baiduUrl = "https://api.map.baidu.com/reverse_geocoding/v3/?ak={ak}&output=json&coordtype=wgs84ll&location={location}";

    @Autowired
    private RestTemplate restTemplate;

    public String requestThirdData(BigDecimal lng,BigDecimal lat) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>();
        map.put("ak", baiduKey);
        map.put("location", lat.toString() + "," + lng.toString());
        String res = restTemplate.getForObject(
                baiduUrl,
                String.class,
                map);
        JSONObject result = JSONObject.parseObject(res);

//        JSONObject result = restTemplate.getForObject(url.replace("lng",lng.toString()).replace("lat",lat.toString()),JSONObject.class);
        if (result == null || result.getIntValue("status") != 0) {
            log.error("获取地址位置失败");
            return null;
        }
        JSONObject regResult = result.getJSONObject("result");
        if (regResult == null){
            log.error("获取地址位置失败");
            return null;
        }
        JSONObject addResult = regResult.getJSONObject("addressComponent");
        if (addResult == null){
            log.error("获取地址位置失败");
            return null;
        }
//        log.error("地理位置编码:" + addResult.getString("adcode"));
        return addResult.getString("adcode");
    }
}
